package com.ruoyi.web.controller.h5.question;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.entity.QnnQuestionnaire;
import com.ruoyi.system.service.QnnQuestionnaireService;
import com.ruoyi.system.vo.SubmitAnswerVO;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/h5/questionnaire")
public class H5QuestionnaireController {

    @Autowired
    private QnnQuestionnaireService questionnaireService;

    /**
     * H5 获取问卷详情（仅可访问已发布且在有效期内、且符合投放范围的问卷）
     */
    @GetMapping("/{id}")
    public AjaxResult getQuestionnaireDetail(@PathVariable Long id, @RequestParam(required = false) String userId) {
        QnnQuestionnaire questionnaire = questionnaireService.getQuestionnaireDetail(id);
        questionnaireService.assertH5Accessible(questionnaire, userId);
        return AjaxResult.success(questionnaire);
    }

    /**
     * H5 提交答卷
     */
    @PostMapping("/answer/submit")
    public AjaxResult submitAnswer(@RequestBody SubmitAnswerVO submitAnswerVO) {
        Long answerSheetId = questionnaireService.submitAnswer(submitAnswerVO);
        return AjaxResult.success(answerSheetId);
    }

    /**
     * H5 可用问卷列表（按模块）
     */
    @GetMapping("/available")
    public AjaxResult listAvailable(@RequestParam Integer module,
                                    @RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    @RequestParam(required = false) String userId) {
        int offset = Math.max(0, (page - 1) * size);
        List<QnnQuestionnaire> rows = questionnaireService.listAvailableForUserByModule(userId, module, offset, size);
        long total = questionnaireService.summaryAvailableByModules(userId, Collections.singletonList(module))
                .getOrDefault(module, 0L);
        java.util.Map<String, Object> data = new java.util.HashMap<>();
        data.put("rows", rows);
        data.put("total", total);
        data.put("page", page);
        data.put("size", size);
        return AjaxResult.success(data);
    }

    /**
     * H5 可用问卷汇总（按模块计数）
     */
    @GetMapping("/available/summary")
    public AjaxResult summary(@RequestParam(required = false) List<Integer> modules,
                              @RequestParam(required = false) String userId) {
        if (modules == null || modules.isEmpty()) {
            modules = Arrays.asList(1,2,3,4);
        }
        Map<Integer, Long> summary = questionnaireService.summaryAvailableByModules(userId, modules);
        return AjaxResult.success(summary);
    }
}


